package cn.edu.hit.selflearning;

import cn.edu.hit.CacheManager;
import cn.edu.hit.core.Document;
import cn.edu.hit.core.conf.ConfigureLoader;
import cn.edu.hit.core.db.*;
import cn.edu.hit.kg.data.CypherRunner;
import cn.edu.hit.kg.data.GraphData;
import cn.edu.hit.kg.data.GraphDataProvider;
import cn.edu.hit.kg.data.Node;
import cn.edu.hit.kg.entity.BaseNode;
import cn.edu.hit.kg.entity.Fault;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.context.request.WebRequest;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

@RestController
public class RedisController {
    static Logger logger = LoggerFactory.getLogger(RedisController.class);
    static DataConnection connection = DataConnectionLoader.getInstance();
    static DataReader reader = connection.getReader();
    static DBReadHelper dbHelper = new DBReadHelper(reader);
    static GraphData graphData = GraphData.getInstance();

    static List<Map<String, Object>> faultList = GetPortandName.listFaults();

    public static final CacheManager cacheManager = CacheManager.getInstance();

//    public Jedis connectJedis(){
//        return cacheManager.getJedis();
//    }

    static final String FAULT_KEY = "end_fault:";
    static final String FEATURE_KEY = "feature_frequency:";
    static final String FAULT_REASON = "fault_reason:";

    @Autowired
    HttpServletRequest request;

//    @CrossOrigin
//    @RequestMapping(method = RequestMethod.GET, value = "/",produces="text/html;charset=UTF-8")
//    public String isRun(){
//        return "<!DOCTYPE html>\n" +
//                "<html>\n" +
//                "<head>\n" +
//                "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" +
//                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\" />\n" +
//                "    <title>发电机组远程故障诊断系统</title>\n" +
//                "    <script>\n" +
//                "        window.baseHost = \"http://"+request.getServerName()+"\";\n" +
//                "        window.basePort = "+request.getServerPort()+";\n" +
//                "    </script>\n" +
//                "    <script type=\"text/javascript\" src=\"script/fault_web.js\"></script>\n" +
//                "    <script src=\"beautifulJson.js\"></script>\n" +
//                "</head>\n" +
//                "<body></body>\n" +
//                "</html>";
//    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * 用来获取已结束的故障
     *
     * @return
     */
    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "faults", produces = "application/json;charset=UTF-8")
    public JSONArray loadFaults() {
//        Jedis jedis = cacheManager.getJedis();
//        jedis.select(1);
        Set<String> keys = cacheManager.getJedis().keys(FAULT_KEY + "*");
        logger.info(keys.toString());
        JSONArray jarr = new JSONArray();
        for (String key : keys) {
            JSONObject fault = new JSONObject();
            long size = cacheManager.getJedis().llen(key);
            JSONArray jsonArray = new JSONArray();
            for (long i = 0; i < size; i++) {
                String json = cacheManager.getJedis().lindex(key, i);
                JSONObject jobj = JSONObject.fromObject(json);
                String keys2 = "feature_frequency:" + jobj.getString("machineNumber") + ":" + jobj.getInt("feature_id");
                if (cacheManager.getJedis().exists(keys2)) {
                    String json2 = cacheManager.getJedis().get(keys2);
                    JSONObject jobj2 = JSONObject.fromObject(json2);
                    jobj.put("quantum", jobj2.get("quantum"));
                    jobj.put("frequency", jobj2.getJSONObject("frequency").get(jobj.getString("fault_id")));
                }
                jobj.put("properties", graphData.getById(jobj.getInt("feature_id")).asMap());

                jsonArray.add(jobj);
                if (i == 0) {
                    fault.put("properties", graphData.getById(jobj.getInt("fault_id")).asMap());
                    JSONObject reason_pr = this.loadReasonFreq(jobj.getString("machineNumber"), jobj.getInt("fault_id"));
                    List<Map> reasons = graphData.getAllSubNodes(jobj.getInt("fault_id"))
                            .filter(node -> node.hasLabel("Reason"))
                            .map(r -> {
                                JSONObject reason = JSONObject.fromObject(r.asMap());
                                reason.put("id", r.id());
                                return reason;
                            }).collect(Collectors.toList());

                    fault.put("reasons", reasons);
                    fault.put("reasons_probability", reason_pr);
                }
            }
            //此处应该添加一个last_timestamp   让ui界面显示故障发生时间
            fault.put("features", jsonArray);
            jarr.add(fault);
        }
//        jedis.close();
        return jarr;
    }

    /**
     * 用来获取实时发生的故障
     *
     * @return
     */
    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "faults2", produces = "application/json;charset=UTF-8")
    public JSONArray loadFaults2() {

        Set<String> keys = cacheManager.getJedis().keys("fault_feature:*");
        JSONArray jarr = new JSONArray();
        for (String key : keys) {
            JSONObject fault = new JSONObject();
            long size = cacheManager.getJedis().llen(key);
            JSONArray jsonArray = new JSONArray();
            for (long i = 0; i < size; i++) {
                String json = cacheManager.getJedis().lindex(key, i);
                JSONObject jobj = JSONObject.fromObject(json);
                String keys2 = "feature_frequency:" + jobj.getString("machineNumber") + ":" + jobj.getInt("feature_id");
                if (cacheManager.getJedis().exists(keys2)) {
                    String json2 = cacheManager.getJedis().get(keys2);
                    JSONObject jobj2 = JSONObject.fromObject(json2);
                    jobj.put("quantum", jobj2.get("quantum"));
                    jobj.put("frequency", jobj2.getJSONObject("frequency").get(jobj.getString("fault_id")));
                }
                Node featurenode = graphData.getById(jobj.getInt("feature_id"));
                JSONObject properties = JSONObject.fromObject(featurenode.asMap());
                properties.put("entityType", featurenode.labels().iterator().next());
                jobj.put("properties", graphData.getById(jobj.getInt("feature_id")).asMap());

                jsonArray.add(jobj);
                if (i == 0) {
                    fault.put("properties", graphData.getById(jobj.getInt("fault_id")).asMap());
                    JSONObject reason_pr = this.loadReasonFreq(jobj.getString("machineNumber"), jobj.getInt("fault_id"));
                    List<Map> reasons = graphData.getAllSubNodes(jobj.getInt("fault_id"))
                            .filter(node -> node.hasLabel("Reason"))
                            .map(r -> {
                                JSONObject reason = JSONObject.fromObject(r.asMap());
                                reason.put("id", r.id());
                                return reason;
                            }).collect(Collectors.toList());

                    fault.put("reasons", reasons);
                    fault.put("reasons_probability", reason_pr);
                }
            }
            //此处应该添加一个last_timestamp   让ui界面显示故障发生时间
            fault.put("features", jsonArray);
            jarr.add(fault);
        }
//        jedis.close();
        return jarr;
    }

    /**
     * 获取推理过程
     *
     * @param machineNumber
     * @param faultId
     * @return
     */
    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "machine/{machineNumber}/{faultId}", produces = "application/json;charset=UTF-8")
    public JSONObject getExplain(@PathVariable("machineNumber") String machineNumber, @PathVariable("faultId") Long faultId) {
        JSONObject jsonObject = new JSONObject();
        JSONObject node = new JSONObject();
        JSONObject edge = new JSONObject();
        Fault fault = Fault.loadById(faultId);
        try {
            String matchii = fault.getMatchedFeature(machineNumber);
            JSONArray array2 = JSONArray.fromObject(matchii);
            jsonObject.put("match", array2);
        } catch (Exception e) {

        }
        List<Long> ids = graphData.getAllSubNodeIds(faultId).collect(Collectors.toList());
        for (int i = 0; i < ids.size(); i++) {

            node.put(ids.get(i), graphData.getById(ids.get(i)).asMap());
            edge.put(ids.get(i), graphData.getAllSubNodeIds(ids.get(i)).collect(Collectors.toList()));
        }
        jsonObject.put("node", node);
        jsonObject.put("edge", edge);
        return jsonObject;
    }


    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "feature/{machineNumber}/{id}", produces = "application/json;charset=UTF-8")
    public JSONObject loadFeature(@PathVariable("machineNumber") String machineNumber, @PathVariable("id") long id, @PathVariable("faultId") long faultId) {
        String freqKey = FEATURE_KEY + machineNumber + ':' + id;
        JSONObject freq;
//        Jedis jedis = connectJedis();
        if (cacheManager.getJedis().exists(freqKey)) {
            freq = JSONObject.fromObject(cacheManager.getJedis().get(freqKey));
        } else {
            GraphData graphData = GraphData.getInstance();
            freq = new JSONObject();
            Node feature = graphData.getById(id);
            if (feature.asMap().get("quantum") == null) {
                freq.put("quantum", 100);
            } else {
                freq.put("quantum", feature.asMap().get("quantum"));
            }
            if (feature.asMap().get("frequency") == null) {
                JSONObject fault = new JSONObject();
                fault.put("" + faultId, 10);
                freq.put("frequency", fault);
            } else {
                JSONObject fault = new JSONObject();
                fault.put("" + faultId, feature.asMap().get("frequency"));
                freq.put("frequency", fault);
            }
        }
//        jedis.close();
        return freq;
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "feature/{id}", produces = "application/json;charset=UTF-8")
    public JSONObject loadFeature(@PathVariable("id") long id) {
        String freqKey = FEATURE_KEY + id;
        JSONObject freq;
//        Jedis jedis = connectJedis();
        if (cacheManager.getJedis().exists(freqKey)) {
            freq = JSONObject.fromObject(cacheManager.getJedis().get(freqKey));
        } else {
            GraphData graphData = GraphData.getInstance();
            freq = new JSONObject();
            Node feature = graphData.getById(id);
            if (feature == null) {
                freq.put("quantum", 100);
                JSONObject aaa = new JSONObject();
                aaa.put(id, 10);
                freq.put("frequency", aaa);
                return freq;
            }
            if (feature.asMap().get("quantum") == null) {
                freq.put("quantum", 100);
            } else {
                freq.put("quantum", feature.asMap().get("quantum"));
            }
            if (feature.asMap().get("frequency") == null) {
                JSONObject aaa = new JSONObject();
                aaa.put(id, 10);
                freq.put("frequency", aaa);
            } else {
                freq.put("frequency", feature.asMap().get("frequency"));
            }
        }
//        jedis.close();
        return freq;
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "reason/{id}", produces = "application/json;charset=UTF-8")
    public JSONObject loadReasonFreq(@PathVariable("id") long fault_id) {
        String freqKey = FAULT_REASON + fault_id;
        JSONObject freq;
//        Jedis jedis = connectJedis();
        if (cacheManager.getJedis().exists(freqKey)) {
            freq = JSONObject.fromObject(cacheManager.getJedis().get(freqKey));
        } else {
//            GraphData graphData = GraphData.getInstance();
            freq = new JSONObject();
            Node fault = graphData.getById(fault_id);
            freq.put("quantum", fault.asMap().getOrDefault("quantum", 100));
            if (fault.asMap().containsKey("frequency")) {
                freq.put("frequency", fault.asMap().getOrDefault("frequency", 10));
            } else {
                freq.put("frequency", graphData.getAllSubNodes(fault_id)
                        .filter(node -> StreamSupport.stream(node.labels().spliterator(), false)
                                .anyMatch(x -> x.equals("Reason")))
                        .collect(Collectors.toMap(x -> "" + x.id(), x -> Double.parseDouble(x.asMap().get("probability").toString()) * 100)));
            }
        }
//        jedis.close();
        return freq;
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "reason/{machineNumber}/{id}", produces = "application/json;charset=UTF-8")
    public JSONObject loadReasonFreq(@PathVariable("machineNumber") String machineNumber, @PathVariable("id") long fault_id) {
        String freqKey = FAULT_REASON + machineNumber + ":" + fault_id;
        JSONObject freq;
//        Jedis jedis = connectJedis();
        if (cacheManager.getJedis().exists(freqKey)) {
            freq = JSONObject.fromObject(cacheManager.getJedis().get(freqKey));
        } else {
//            GraphData graphData = GraphData.getInstance();
            freq = new JSONObject();
            Node fault = graphData.getById(fault_id);
            freq.put("quantum", fault.asMap().getOrDefault("quantum", 100));
            if (fault.asMap().containsKey("frequency")) {
                freq.put("frequency", fault.asMap().get("frequency"));
            } else {
                freq.put("frequency", graphData.getAllSubNodes(fault_id)
                        .filter(node -> StreamSupport.stream(node.labels().spliterator(), false)
                                .anyMatch(x -> x.equals("Reason")))
                        .collect(Collectors.toMap(x -> "" + x.id(), x -> Double.parseDouble(x.asMap().get("probability").toString()) * 100)));
            }
        }
//        jedis.close();
        return freq;
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "train/{machineNumber}/{id}", produces = "application/json;charset=UTF-8")
    public JSONObject train(@PathVariable("machineNumber") String machineNumber, @PathVariable("id") String reportId, @RequestParam("features") String fs, @RequestParam("reasons") String reasons) {
        fs = fs.substring(1, fs.length() - 1);
        String[] strArray = fs.split(",");
        ArrayList list = new ArrayList();
        for (int i = 0; i < strArray.length; i++) {
            list.add(strArray[i]);
        }
//        System.out.println(list);
//        Jedis jedis = connectJedis();
//        String line = jedis.lpop(FAULT_KEY+reportId);
        String line = cacheManager.getJedis().lpop("fault_feature:" + machineNumber + ":" + reportId);
        JSONObject faultJson = JSONObject.fromObject(line);
        long faultId = faultJson.getLong("fault_id");

        for (int i = 0; i < list.size(); i++) {
            long featureId = Long.parseLong(list.get(i).toString());
            JSONObject Featurefreq = loadFeature(machineNumber, featureId, faultId);
            Featurefreq.put("quantum", Featurefreq.optInt("quantum") + 1);
            Featurefreq.getJSONObject("frequency").put("" + faultId, Featurefreq.getJSONObject("frequency").optInt("" + faultId) + 1);
            //Featurefreq.put("frequency",Featurefreq.optInt("frequency")+1);
            String freqKey = FEATURE_KEY + machineNumber + ":" + featureId;
            String res = Featurefreq.toString();
            cacheManager.getJedis().set(freqKey, res);
        }

        reasons = reasons.substring(1, reasons.length() - 1);
        String[] strArray2 = reasons.split(",");
        ArrayList list2 = new ArrayList();
        for (int i = 0; i < strArray2.length; i++) {
            list2.add(strArray2[i]);
        }

        JSONObject reasonFreq = loadReasonFreq(machineNumber, faultId);
        for (int i = 0; i < list2.size(); i++) {
            long reason = Long.parseLong(list2.get(i).toString());
            reasonFreq.put("quantum", reasonFreq.optInt("quantum") + 1);
            reasonFreq.getJSONObject("frequency").put("" + reason, reasonFreq.getJSONObject("frequency").optInt("" + reason) + 1);
        }

        cacheManager.getJedis().set(FAULT_REASON + machineNumber + ":" + faultId, reasonFreq.toString());

        cacheManager.getJedis().del(FAULT_KEY + reportId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", true);
//        jedis.close();
        logger.info("已训练reportId:{}", reportId);
        return jsonObject;
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "clear/{id}", produces = "application/json;charset=UTF-8")
    public JSONObject clear(@PathVariable("id") String reportId) {
//        Jedis jedis = connectJedis();
        cacheManager.getJedis().del(FAULT_KEY + reportId);
//        System.out.println("已删除faultId："+faultId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", true);
//        jedis.close();
        logger.info("已删除reportId：{}", reportId);
        return jsonObject;
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.POST, value = "cypher", produces = "application/json;charset=UTF-8")
    public List<Map<String, Object>> executeCypher() {
        String cypher = request.getParameter("cypher");
        GraphDataProvider provider = GraphDataProvider.getInstance();
        if (provider instanceof CypherRunner) {
            CypherRunner cypherRunner = (CypherRunner) provider;
            return cypherRunner.runCyper(cypher);
        }
        return Collections.emptyList();
    }

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "graph/faults", produces = "application/json;charset=UTF-8")
    public List<Map<String, Object>> listFaults() {
        return faultList;
    }


    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, value = "rsfault/faultData/faults/{ids}", produces = "application/json;charset=UTF-8")
    public JSONObject getFaultByJoinSystemId(@PathVariable("ids") String ids) {
        String machineNum = "";
        try {
            String[] idArray = StringUtils.split(ids, ',');
            if (idArray[0] != null) {
                machineNum = idArray[0].substring(0, idArray[0].length() - 7);
            }
            logger.debug("ArraySize:" + idArray.length);

            GraphData graphData = GraphData.getInstance();

            List<Node> faults2 = graphData.getByLabel("Fault")
                    .filter(node ->
                            Stream.of(idArray)
                                    .map(id -> id.substring(id.length() - 7))
                                    .anyMatch(Predicate.isEqual(node.get("outId").toString())))
                    .collect(Collectors.toList());

            List<JSONObject> faults = new ArrayList<>();

            for (int i = 0; i < faults2.size(); i++) {
                faults.add(packJoinSystemFaultToJsonObject(faults2.get(i), machineNum));
            }

            logger.debug("FaultSize:" + faults.size());

            List<JSONObject> result = Stream.of(idArray).sequential().map(id -> {
                Optional<JSONObject> optional = faults.stream().filter(json ->
                        id.substring(id.length() - 7).equals(json.get("moduleId"))).findAny();
                if (optional.isPresent()) {
                    JSONObject jsonObject = JSONObject.fromObject(optional.get());
                    jsonObject.put("platform_id", id);
                    logger.debug("In Line128:" + id);
                    return jsonObject;
                } else {
                    logger.warn("Fault " + id + " not found!");
                    return null;
                }

            }).filter(x -> x != null).sorted(Comparator.comparingInt(json -> json.optBoolean("isOpen", false) ? -1 : 1)).collect(Collectors.toList());

            return packMessage200(result);
        } catch (Exception e) {
            return packMessageError(e);
        }
    }

    private JSONObject packJoinSystemFaultToJsonObject(Node node, String machineNum) {
        if (node != null && node.hasLabel("Fault")) {
            Fault faultNode = new Fault(node);

            String freqKey = "fault_reason:" + machineNum + ":" + faultNode.getId();  //每个原因的置信度应该与机器相关
            List<Map<String, Object>> reasonMatched;
            if (cacheManager.getJedis().exists(freqKey)) {
                JSONObject freq = JSONObject.fromObject(cacheManager.getJedis().get(freqKey));
                reasonMatched = BaseNode.getAllSubNodes(faultNode.getId())
                        .map(BaseNode::loadNodeById)
                        .filter(r -> r.node.hasLabel("Reason"))
                        .map(r -> {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", r.node.get("name"));
                            map.put("solution", r.node.get("solution"));
                            int quantum = freq.getInt("quantum");
                            int frequency = freq.optJSONObject("frequency").optInt("" + r.getId());
                            map.put("probability", frequency * 1.0 / quantum);
                            return map;
                        }).collect(Collectors.toList());
            } else {
                reasonMatched = BaseNode.getAllSubNodes(faultNode.getId())
                        .map(BaseNode::loadNodeById)
                        .filter(r -> r.node.hasLabel("Reason"))
                        .map(r -> {
                            Map<String, Object> map = new HashMap<>();
                            map.put("name", r.node.get("name"));
                            map.put("solution", r.node.get("solution"));
                            int quantum = Integer.parseInt("" + faultNode.node.asMap().getOrDefault("quantum", 100));
                            int frequency = 0;
                            if (faultNode.node.asMap().containsKey("frequency")) {
                                JSONObject freq = JSONObject.fromObject(faultNode.node.asMap().get("frequency"));
                                frequency = freq.optInt("" + r.getId(), 0);
                            } else {
                                map.put("probability", Double.parseDouble(r.getString("probability")));
                                return map;
                            }
                            map.put("probability", frequency * 1.0 / quantum);
                            return map;
                        }).collect(Collectors.toList());
            }


            List<String> portNames = new ArrayList<>();
            List<String> featureMatched = BaseNode.getAllSubNodes(faultNode.getId())
                    .map(BaseNode::loadNodeById)
                    .filter(r -> r.node.hasLabel("Feature"))
                    .map(feature -> {
                        return (String) feature.node.get("name");
                    })
                    .collect(Collectors.toList());
            for (int i = 0; i < featureMatched.size(); i++) {
                List<Document> channelList = reader.queryByTemplate(Filters.eq("signalType", featureMatched.get(i)));
                for (int j = 0; j < channelList.size(); j++) {
                    String channelIdStr = channelList.get(j).getString("CombineChanenels");
                    String[] IdArray = channelIdStr.substring(1, channelIdStr.length() - 1).split(",");
                    for (int k = 0; k < IdArray.length; k++) {
                        String portId = IdArray[k];
                        if (portId.length() > 5) {
                            Document portDocunment = dbHelper.getById(portId.substring(1, portId.length() - 1));
                            if (portDocunment != null) {
                                String portName = portDocunment.getString("dataSourceArgs");
                                boolean hasport = false;
                                for (int l = 0; l < portNames.size(); l++) {
                                    if (portNames.get(l).equals(portName)) {
                                        hasport = true;
                                    }
                                }
                                if (!hasport) {
                                    portNames.add(portName);
                                }
                            }
                        }
                    }
                }
            }

            List<JSONObject> reasons = new ArrayList<>();
            for (int i = 0; i < reasonMatched.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("reasonName", reasonMatched.get(i).get("name"));
                jsonObject.put("solution", reasonMatched.get(i).get("solution"));
                jsonObject.put("probability", reasonMatched.get(i).get("probability"));
                reasons.add(jsonObject);
            }

            JSONObject json = new JSONObject();
            json.put("faultId", node.id());
            json.put("faultName", node.getOrDefault("name", ""));
            json.put("moduleName", node.getOrDefault("faultModule", ""));
            json.put("phenomenon", node.getOrDefault("suggest_description", ""));
            json.put("part", node.getOrDefault("location", ""));
            json.put("faultLevel", node.get("suggest"));
            json.put("suggest", node.get("suggest"));
            json.put("reasons", reasons);
            json.put("showType", 1);
            json.put("moduleId", node.get("outId"));
            json.put("signalPointIds", portNames);
            return json;
        } else {
            logger.warn("Not a valid FaultNode");
            return new JSONObject(true);
        }
    }

    private JSONObject packMessage200(Object data) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("userMessage", "获取信息成功");
        jsonObject.accumulate("internalMessage", "获取信息成功");
        jsonObject.accumulate("code", 0);
        jsonObject.accumulate("status", "SUCCESS");
        jsonObject.accumulate("moreInfo", "");
        jsonObject.accumulate("data", data);
        return jsonObject;
    }

    private JSONObject packMessageError(Throwable throwable) {
        throwable.printStackTrace();
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("userMessage", "获取信息失败");
        jsonObject.accumulate("internalMessage", "获取信息失败");
        jsonObject.accumulate("code", 500);
        jsonObject.accumulate("status", "EXCEPTION");
        jsonObject.put("moreInfo", throwable.getMessage());
//        jsonObject.accumulate("moreInfo",throwable.getMessage());
        return jsonObject;
    }

//    @CrossOrigin
//    @RequestMapping(method = RequestMethod.GET, value = "explain/{machineNumber}/{id}",produces="application/json;charset=UTF-8")
//    public JSONObject togetExplain(@PathVariable("machineNumber")String machineNumber,@PathVariable("id")Long faultId) {
//        getExplain(faultId,machineNumber)
//        return new JSONObject();
//    }
//

}
